//
//  PlayVideoVC.m
//  PlayerVH
//
//  Created by 彭冲 on 24/5/18.
//  Copyright © 2018年 彭冲. All rights reserved.
//

#import "PlayVideoVC.h"
#import <AliyunPlayerSDK/AlivcMediaPlayer.h>
#import "AAAVC.h"
#import "Masonry.h"

#define screenH [UIScreen mainScreen].bounds.size.height
#define screenW [UIScreen mainScreen].bounds.size.width


@interface PlayVideoVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) BOOL isFullScreen;
@property (nonatomic, assign) BOOL statusBarHidden;

//是否监听屏幕旋转，防止在push到下个页面，还监听屏幕旋转的通知，
//并且，如果全屏下涉及到push，就先把屏幕旋转正再去push，避免push出的页面是横屏，参考虎牙
@property (nonatomic, assign) BOOL isObserve;

@property (nonatomic, strong) UIView *playerView;//播放器最底部的父view
@property (nonatomic, strong) AliVcMediaPlayer *mediaPlayer; //阿里播放器
@property (nonatomic, strong) UIView *controllView; //播放器上的各个控制按钮，全屏按钮等
@property (nonatomic, strong) UIView *contentView; //阿里播放器需要的载体view
@property (nonatomic, strong) UIButton *fullBtn;
@property (nonatomic, strong) UIButton *backB;


@property (nonatomic, strong) UITableView *tableView;

//@property (nonatomic, assign) int tempLandSpace; //记录横屏状态，防止横屏转横屏出问题


@end

@implementation PlayVideoVC


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.isObserve = YES; //页面全部显示完，重新执行监听通知代码
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.isObserve = NO; //即将消失，就不处理屏幕旋转了
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor purpleColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    self.playerView = [[UIView alloc] init];
    self.playerView.layer.masksToBounds = YES;
    self.contentView = [[UIView alloc] init];
    self.controllView = [[UIView alloc] init];
    self.backB = [[UIButton alloc] init];
    self.backB.backgroundColor = [UIColor orangeColor];
    [self.backB addTarget:self action:@selector(backBClick) forControlEvents:64];
    [self.backB setTitle:@"返回" forState:0];
    
    UITapGestureRecognizer *videoClickTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(videoClickTap)];
    [self.controllView addGestureRecognizer:videoClickTap];
    
    UITextField *ft = [[UITextField alloc] init];
    ft.placeholder = @"这儿是输入框，去发弹幕吧";
    ft.backgroundColor = [UIColor greenColor];
    ft.textAlignment = NSTextAlignmentCenter;
    
    
    self.fullBtn = [[UIButton alloc] init];
    [self.fullBtn setTitle:@"全屏" forState:0];
    self.fullBtn.backgroundColor = [UIColor redColor];
    [self.fullBtn addTarget:self action:@selector(fullBtnClick) forControlEvents:64];

    self.tableView = [[UITableView alloc] init];
    self.tableView.rowHeight = 50;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.view addSubview:self.playerView];
    [self.playerView addSubview:self.contentView];//用来装播放器
    [self.playerView addSubview:self.controllView];//用来装控制各个按钮
    [self.controllView addSubview:ft];
    [self.controllView addSubview:self.fullBtn];
    [self.controllView addSubview:self.backB];

    [self.view addSubview:self.tableView];

    
    [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.equalTo(self.view.mas_top);
        make.right.equalTo(self.view.mas_right);
        make.height.mas_equalTo(screenW*(screenW/screenH));
    }];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.playerView);
    }];
 
    [self.controllView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.playerView);
    }];
    
    [self.backB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.controllView).offset(20);
        make.left.equalTo(self.controllView).offset(10);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(30);
    }];

    [self.fullBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.controllView).offset(0);
        make.bottom.equalTo(self.controllView);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(30);
    }];
    
    [ft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.controllView).offset(50);
        make.left.equalTo(self.controllView).offset(50);
        make.right.equalTo(self.controllView).offset(-50);
        make.height.mas_equalTo(40);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.playerView.mas_bottom);
        make.bottom.equalTo(self.view);
    }];
    
    
    [self setupPlayer];

//    加载页面，初始化状态，不全屏，不隐藏状态栏
    self.isFullScreen = NO;
    self.statusBarHidden = NO;
}

- (void)setupPlayer {
    //创建播放器
    self.mediaPlayer = [[AliVcMediaPlayer alloc] init];
    [self.mediaPlayer create:self.contentView];
    self.mediaPlayer.mediaType = MediaType_AUTO;
    //设置超时时间，单位为毫秒
    self.mediaPlayer.timeout = 25000;
    //缓冲区超过设置值时开始丢帧，单位为毫秒。直播时设置，点播设置无效。范围：500～100000
    self.mediaPlayer.dropBufferDuration = 8000;
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"xiaoming" ofType:@"mp4"];
//    NSURL *url = [NSURL fileURLWithPath:path];
    //网络视频，填写网络url地址
    NSURL *url = [NSURL URLWithString:@"https://media.w3.org/2010/05/sintel/trailer.mp4"];
    //prepareToPlay:此方法传入的参数是NSURL类型.
    AliVcMovieErrorCode err = [self.mediaPlayer prepareToPlay:url];
    if (err == ALIVC_SUCCESS) {
        [self.mediaPlayer play];
    }
}

- (void)backBClick {
    if (self.isFullScreen == YES) {
        [self fullBtnClick];
    }else{
        [self.mediaPlayer stop];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)fullBtnClick {
//    手动点击屏幕右转
    [self setFullScreen:UIInterfaceOrientationLandscapeRight];
}

- (void)videoClickTap {
    
    [self.view endEditing:YES];
    self.statusBarHidden = !self.statusBarHidden;
    [UIView animateWithDuration:0.3 animations:^{
        [self setNeedsStatusBarAppearanceUpdate];
    }];
}
    

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

- (BOOL)prefersStatusBarHidden {
    return self.statusBarHidden;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent; //显示白色
}

#pragma mark 设置是否全屏播放
- (void)setFullScreen:(UIInterfaceOrientation)orientation {
    
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    }else{
        NSNumber *value = [NSNumber numberWithInt:UIDeviceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    }
}
- (void)orientChange:(NSNotification *)noti {
    //    NSDictionary* ntfDict = [noti userInfo];
    
    if (self.isObserve == NO) { //push到下个页面，就不处理屏幕旋转的代码了
        return;
    }
    
    
    UIDeviceOrientation  orient = [UIDevice currentDevice].orientation;
    switch (orient) {
        case UIDeviceOrientationPortrait:{
            [self.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(screenW*(screenW/screenH));
            }];
            self.isFullScreen = NO;
            break;
        }
        
        case UIDeviceOrientationLandscapeLeft:{

            //因为屏幕旋转，宽高颠倒，所以，此时需要设置高度还是屏幕高度。
            [self.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
               make.height.mas_equalTo(screenH);
            }];
            self.isFullScreen = YES;
            break;
        }
            
        case UIDeviceOrientationLandscapeRight:{
            [self.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(screenH);
            }];
            self.isFullScreen = YES;
            break;
        }
            
        case UIDeviceOrientationPortraitUpsideDown: //手机没这个情况，pad有
            break;

        default:
            break;
    }
    
}

/**
#pragma mark 旋转方法的监听 iOS8的方法，已经y弃用
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    
    if (toInterfaceOrientation == UIDeviceOrientationPortrait) {  //--->竖屏
        self.playerView.sd_layout
        .leftEqualToView(self.view)
        .topEqualToView(self.view)
        .widthIs(screenH)
        .heightIs(200);
        self.tempLandSpace = 1;
        self.isFullScreen = NO;
    }else{
        
        if ((self.tempLandSpace == 3 && toInterfaceOrientation == 4) || (self.tempLandSpace == 4 && toInterfaceOrientation == 3)) {
            
            self.tempLandSpace = toInterfaceOrientation;
            return;
        }
        
        self.playerView.sd_layout
        .leftEqualToView(self.view)
        .rightEqualToView(self.view)
        .widthIs(screenH)
        .heightIs(screenW);
        
        self.tempLandSpace = toInterfaceOrientation;
        self.isFullScreen = YES;
    }
    
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    
}
 **/

#pragma mark tableview delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell_ID"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell_ID"];
    }
    cell.textLabel.text = @"一起学🐈叫，喵喵喵喵喵！！！一起学🐈叫，喵喵喵喵喵！！！一起学🐈叫，喵喵喵喵喵！！！一起学🐈叫，喵喵喵喵喵！！！";
    cell.imageView.image = [UIImage imageNamed:@"liveCover"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    AAAVC *aa = [[AAAVC alloc] init];
    [self setFullScreen:UIInterfaceOrientationPortrait];
    [self.navigationController pushViewController:aa animated:YES];
}

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"666_SundPrint_999:%@", @"dealloc");
}
@end
